package com.young.shop.filter;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.regexp.internal.RE;
import com.young.shop.pojo.vo.BaseRespVO;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet()
public class LoginFilter implements Filter {
    private List<String> whiteList = new ArrayList<>();

    {
        whiteList.add("/login");
    }
    @Override
    public void doFilter(ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String requestURI = req.getRequestURI();
        boolean ifExist = whiteList.stream().anyMatch(item->{
            return requestURI.contains(item);
        });
        if (ifExist){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        HttpSession session = req.getSession();
        Object sessionClient = session.getAttribute("client");
        if (session==null||sessionClient==null){
            BaseRespVO objectBaseRespVO = new BaseRespVO();
            objectBaseRespVO.setCode(100);
            objectBaseRespVO.setMsg("未登录，请登录！");
            String jsonString = JSON.toJSONString(objectBaseRespVO);
            resp.getWriter().write(jsonString);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
